package com.sikaryofficial.backend.service.points;

import com.sikaryofficial.backend.constant.RedisCacheKey;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * @author : qinjinyuan
 * @desc : 浏览并点赞官方发布文章得积分服务
 * @date : 2023/10/31 19:03
 */
@Service(value = PointRuleConstant.ARTICLE_VIEW_LIKE + IPointsDetailStrategy.SUFFIX)
@Slf4j
public class ArticleViewLikeService extends AbstractPointService {
    @Resource
    private RedisService redisService;
    /**
     * 增加积分后校验
     *
     * @param userId
     * @return
     */
    @Override
    public boolean updatePoints(Long sourceId, Long userId) {
        // 构建用户对特定文章获取积分的唯一标识key
        String articleViewLikeUnionKey = buildUnionKey(RedisCacheKey.ARTICLE_VIEW_LIKE_POINTS_UNION, sourceId, userId);
        // 检查 sourceId 与 userId 对只能得一次积分
        if (redisService.hasKey(articleViewLikeUnionKey)) {
            log.info("用户{}已对文章{}获得过积分，跳过重复处理", userId, sourceId);
            return false;
        }
        // 自助评价，当积分大于上限，则不继续增加积分
        boolean isOver = checkPointsOver(userId, PointRuleConstant.ARTICLE_VIEW_LIKE, RedisCacheKey.ARTICLE_VIEW_LIKE_POINTS_NUM);
        if (!isOver) {
            // 没有超，则可以继续更新积分
            this.increasePoints(sourceId, userId, PointRuleConstant.ARTICLE_VIEW_LIKE, "");
            // 增加后，进行统计缓存设置
            this.afterIncrease(userId, RedisCacheKey.ARTICLE_VIEW_LIKE_POINTS_NUM);
            // 缓存用户对文章的积分获取时间
            redisService.setCacheObject(articleViewLikeUnionKey, System.currentTimeMillis(), 24L, TimeUnit.HOURS);
            return true;
        }
        return false;
    }
}
